/**
 * Created by apple on 16/3/31.
 */
import template from './corpAdd.view.html';
import viewController from './corpAdd.controller';

class Controller {
    constructor (systemService, $rootScope, uiNotification, statusMap, $location, $state, $stateParams, $uiModal, $cookies, localStorageService) {
        "ngInject"
        this.notify      = uiNotification;
        this.uiModal     = $uiModal;
        this.service     = systemService;
        this.status      = statusMap;
        this.location    = $location;
        this.state       = $state;
        this.localstore  = localStorageService;

        // 树状菜单逻辑
        this.treeNode    = null;
        this.dataList    = [];
        this.records     = [];
        this.child       = true;
        this.parentOrgId = null;
        this.currentNode = "";
        this.currentView = {};
        this.cache       = {};
        this.treeData    = {
            orgId: $cookies.get('rzOrgId')
        }

        this.page = systemService.page;

        angular.extend(this.page, {
            currentPage: $stateParams.page ? $stateParams.page : 1,
            totalItems : ""
        })

        // 获取根树
        systemService.getTree(this.treeData).then((res) => {
            __DEBUG__ && console.log('TreeLoad', Date.now())
            __DEBUG__ && console.log(res)
            if ( res.data && res.data.length ) {
                this.treeNode    = res.data;
                this.node        = res.data[ 0 ];
                this.orgId       = res.data[ 0 ][ 'orgId' ];
                this.parentOrgId = res.data[ 0 ][ 'orgId' ];
                this.currentNode = res.data[ 0 ][ 'orgName' ];
                this.currentView = res.data[ 0 ];
                this.cache[res.data[ 0 ][ 'orgId' ]] = res.data[0]['nodes'];
                this.dataList = this.cache[res.data[ 0 ][ 'orgId' ]];
                localStorageService.set('corp.path', [res.data[ 0 ][ 'orgName' ]]);
            }
        }).finally(() => {
            this.isTreeLoad  = true;
            delete this.treeData.orgId;
        })
    }

    selectNode (scope, node) {
        let treePoints = [];
        let $parent = scope.$nodeScope.$parentNodeScope;
        let $node   = scope.$nodeScope;

        // 树的路径信息
        treePoints.push(scope.$nodeScope.$modelValue.orgName);
        if ($parent) {
            angular.element('.tree-root').removeClass('active')
            let tempNode = $parent;
            tempNode.$element.removeClass('active');
            while (tempNode) {
                tempNode.$element.find('.active').removeClass('active');
                treePoints.push(tempNode.$modelValue.orgName);
                tempNode = tempNode.$parentNodeScope
            }
            this.currentNode = treePoints.reverse().join('<i class="fa fa-angle-right"></i>');
        } else {
            $node.$element.find('.active').removeClass('active');
            this.currentNode = $node.$modelValue.orgName;
        }
        $node.$element.addClass('active');
        this.localstore.set('corp.path', treePoints);
        this.node        = node;
        this.currentView = node;
        this.orgId       = node.orgId;
        this.parentOrgId = node.parentOrgId;
        if (this.node.hasChildren) {
            if (this.cache[node.orgId] && this.cache[node.orgId].length) {
                node.nodes = this.cache[node.orgId];
                this.dataList = this.cache[node.orgId];
                return;
            } else {
                node.loading              = true;
                this.treeData.parentOrgId = node.orgId;
                this.service.getTree(this.treeData).then((res)=> {
                    this.cache[ node.orgId ] = res.data;
                    this.dataList            = this.cache[ node.orgId ];
                    node.nodes               = this.cache[ node.orgId ];
                }).finally(function () {
                    node.loading = false;
                });
            }
        } else {
            this.cache[ node.orgId ] = [];
            this.dataList            = this.cache[ node.orgId ];
            this.child               = node.hasChildren;
        }
        __DEBUG__ && console.log(this.cache)
    }

    toggleNode (scope, node, $event) {
        $event.preventDefault();
        //if (!node.hasChildren) return
        let treePoints = [];
        let $parent = scope.$nodeScope.$parentNodeScope;
        let $node   = scope.$nodeScope;
        treePoints.push(scope.$nodeScope.$modelValue.orgName);
        if ($parent) {
            let tempNode = $parent;
            while (tempNode) {
                treePoints.push(tempNode.$modelValue.orgName);
                tempNode = tempNode.$parentNodeScope
            }
            this.currentNode = treePoints.reverse().join('<i class="fa fa-angle-right"></i>')
        } else {
            this.currentNode = $node.$modelValue.orgName
        }
        this.localstore.set('corp.path', treePoints);
        this.node        = node;
        this.currentView = node;
        this.orgId       = node.orgId;
        this.parentOrgId = node.parentOrgId;
        if ( scope.collapsed ) {
            scope.expand();
            if (this.cache[node.orgId] && this.cache[node.orgId].length) {
                node.nodes = this.cache[node.orgId];
                this.dataList = this.cache[node.orgId];
                return;
            }
            if ( node.hasChildren ) {
                node.loading              = true;
                this.treeData.parentOrgId = node.orgId;
                this.service.getTree(this.treeData).then((res)=> {
                    this.cache[node.orgId]=res.data;
                    node.nodes = this.cache[node.orgId];
                }).finally(function () {
                    node.loading = false;
                });
            } else {
                this.cache[node.orgId] = []
                this.dataList = this.cache[node.orgId];
                this.pager    = false;
            }
        } else {
            scope.collapse();
        }
    }

    toggleConfirm (item) {
        item.confirm = !item.confirm;
    }

    goDetail (params, node) {
        let path = this.localstore.get('corp.path');
        path.push(node);
        this.localstore.set('corp.path', _.unique(path));
        this.state.go('corp/detail', params)
    }

    del (type, id) {
        this.service.delItem(type, {
            orgId: id
        }).then(() => {
            let idx = _.findIndex(this.cache[this.orgId], {orgId: id});
            this.cache[this.orgId].splice(idx, 1);
            if (this.cache[this.orgId].length == 0) {
                this.child = false;
                this.node.hasChildren = false;
            }
            this.notify.success({
                'title'  : '提示',
                'message': '操作成功!'
            });
        }).catch((data) => {
            this.notify.error({
                'title'  : '提示',
                'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
            });
        })
    }

    changePage (currentPage) {
        this.location.search('page',currentPage);
        this.dataList = [];
        this.dataList = this.records.slice((currentPage - 1) * this.page.perPage, currentPage * this.page.perPage);
    }

    openView (size) {

        if ( !this.orgId ) {
            return this.notify.warning({
                'title'  : '提示',
                'message': '请选择父级节点!'
            });
        }

        let modalInstance = this.uiModal.open({
            animation   : true,
            templateUrl : template,
            controller  : viewController,
            controllerAs: 'vm',
            size        : size,
            resolve     : {
                orgId: this.orgId
            }
        });

        // 处理对话框提交/关闭
        modalInstance.result.then((res) => {
            this.node.hasChildren = true;
            this.cache[this.orgId].push(res);
            this.node.nodes = this.cache[this.orgId];
        });
    }
}

export default Controller;